// pages/home/home.js
import api from '../../utils/api';
var util = require('../../utils/util.js');
import Toast from '@vant/weapp/toast/toast';
import Dialog from '@vant/weapp/dialog/dialog';
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        gradientColor: {
            '0%': '#ffd01e',
            '100%': '#ee0a24',
        },
        planList: null,
        detailinfo: null,
        dong: null,
        da: [],
        daText: '打卡',
        index: null,
        percentage: 0,
        mottoInfo:null,
        mottoauthor:null,
        userData:null
    },
    deleteInfoTap() {
        Dialog.confirm({
                title: '神明大人，确定删除任务吗？'
            })
            .then(() => {
                let value = {
                    plan_id: this.data.detailinfo.plan_id,
                    is_delete: 1
                }
                api.postUpdatePlan(value).then((res) => {
                    // console.log(res)
                    this.setData({
                        dong: 'dongChu'
                    })
                    this.inital()
                })
            })
            .catch(() => {});
    },
    planDetailTap(e) {
        this.setData({
            detailinfo: this.data.planList[e.currentTarget.dataset.index],
            dong: 'dongJin',
            index: e.currentTarget.dataset.index
        })
    },
    detailClose() {
        this.setData({
            dong: 'dongChu'
        })
    },
    dakaTap() {
        // 获取时间
        let date = new Date();
        const hour = date.getHours()
        const minute = date.getMinutes()
        let val = parseInt(hour) * 60 + parseInt(minute)
        let aaa = true
        for (let [k, v] of this.data.planList.entries()) {
            let L1 = v.startTime.split(':')
            let L1val = parseInt(L1[0]) * 60 + parseInt(L1[1])
            let L2 = v.endTime.split(':')
            let L2val = parseInt(L2[0]) * 60 + parseInt(L2[1])
            let arr = 'da[' + (k) + ']'
            if (val > L1val && val < L2val && this.data.da[k] != 'da') {
                let percentage=parseInt(this.data.percentage + 100 / this.data.planList.length)==99?100:parseInt(this.data.percentage + 100 / this.data.planList.length)
                this.setData({
                    [arr]: 'da',
                    percentage:percentage
                })
                let value = {
                    plan_id: v.plan_id,
                    rest: '1'
                }
                api.postUpdatePlan(value).then((res) => {
                    // console.log(res)
                })
                let totalTime={
                    totalTime:parseInt(app.globalData.userInfo.totalTime)+parseInt(v.duration)
                }
                api.updateUserInfo(totalTime).then((res) => {
                    if (res.status == '0') {
                        Toast('打卡成功~');
                        app.globalData.userInfo.totalTime=app.globalData.userInfo.totalTime+parseInt(v.duration) 
                    } else {
                        Toast('打卡失败！');
                    }
                })
                aaa = false
            } else if (val > L1val && val < L2val && this.data.da[k] == 'da') {
                aaa = false
                Toast('您已经打过卡了哦~');
            }
        }
        if (aaa) {
            Toast('暂无打卡任务~');
        }
    },
    addPlan() {
        wx.navigateTo({
            url: '/pages/add/add'
        })
    },
    updateInfoTap() {
        if (this.data.detailinfo.rest == '1') {
            Toast('已打卡信息不支持修改~');
        } else {
            var model = JSON.stringify(this.data.detailinfo);
            wx.navigateTo({
                url: '/pages/add/add?model=' + model + '&is_jia=' + 0,
            })
        }
    },
    listPlan() {
        wx.navigateTo({
            url: '/pages/planlist/planlist'
        })
    },
    startTap() {
        if (app.globalData.userInfo.email) {
            let info = 'detailinfo.is_Start'
            let Iteminfo = 'planList[' + (this.data.index) + '].is_Start'
            this.setData({
                [info]: this.data.detailinfo.is_Start == 1 ? 0 : 1,
                [Iteminfo]: this.data.planList[this.data.index].is_Start == 1 ? 0 : 1
            })
            // 发请求
            let value = {
                plan_id: this.data.detailinfo.plan_id,
                is_Start: this.data.detailinfo.is_Start
            }
            api.postUpdatePlan(value).then((res) => {
                Toast('设置成功~');
            })
        } else {
            Toast('请先在‘我的’页面设置邮箱~');
        }

    },
    endTap() {
        if (app.globalData.userInfo.email) {
            let info = 'detailinfo.is_End'
            let Iteminfo = 'planList[' + (this.data.index) + '].is_End'
            this.setData({
                [info]: this.data.detailinfo.is_End == 1 ? 0 : 1,
                [Iteminfo]: this.data.planList[this.data.index].is_End == 1 ? 0 : 1
            })
            let value = {
                plan_id: this.data.detailinfo.plan_id,
                is_End: this.data.detailinfo.is_End
            }
            api.postUpdatePlan(value).then((res) => {Toast('设置成功~');})
        } else {
            Toast('请先在‘我的’页面设置邮箱~');
        }
    },
    
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        wx.setStorageSync('aShow', false);
        this.inital()
    },
    motto(){
        api.getMottoInfo().then((res) => {
            // console.log(res)
            this.setData({
                mottoInfo:res.data[0].motto,
                mottoauthor:res.data[0].author,
            })
        })
    },
    inital() {
        let time = util.formatTime(new Date());
        let value = {
            start: time,
            end: time
        }
        api.postSelectPlan(value).then((res) => {
            this.setData({
                planList: res.result,
                percentage: 0,
                dong: null
            })
            if (res.status == 1) {
                this.setData({
                    planList: []
                })
            }
            for (const key in this.data.planList) {
                let dates = this.data.planList[key].date.substring(0, 10)
                let datelist = dates.split('-')
                datelist[2] = parseInt(datelist[2]) + 1
                if (datelist[2] / 10 < 1) {
                    datelist[2] = `0${datelist[2]}`
                }
                let arr = 'da[' + (key) + ']'
                dates = datelist.join("-")
                let planList = 'planList[' + (key) + '].date'
                this.setData({
                    [planList]: dates
                })
                if (this.data.planList[key].rest == '1') {
                    let percentage=parseInt(this.data.percentage + 100 / this.data.planList.length)==99?100:parseInt(this.data.percentage + 100 / this.data.planList.length)
                    this.setData({
                        percentage:percentage
                    })
                }
                if (this.data.planList[key].rest == '1') {
                    this.setData({
                        [arr]: 'da'
                    })
                } else {
                    this.setData({
                        [arr]: 'unda'
                    })
                }
            }
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        var page = this;
        let aShow = '';
        //获取存储信息
        wx.getStorage({
            key: 'aShow',
            success: function (res) {
                aShow = res.data;
                if (aShow) {
                    page.inital()
                    wx.setStorageSync('aShow', false)
                }
            }
        })
        
        setTimeout(()=>{
            console.log(app.globalData.userInfo)
            this.setData({
                userData: app.globalData.userInfo.notice
            })
            this.motto()
        },1000)
    },
    noticeClose(){
        let value={
            notice:0
        }
        api.updateUserInfo(value).then((res) => {
            if (res.status == '0') {
            } else {
                Toast('关闭失败！');
            }
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})